package com.gexiaobao.pigeon.ui.fragment.match

import android.os.Bundle
import com.amap.api.services.core.AMapException
import com.amap.api.services.weather.LocalWeatherForecastResult
import com.amap.api.services.weather.LocalWeatherLive
import com.amap.api.services.weather.LocalWeatherLiveResult
import com.amap.api.services.weather.WeatherSearch
import com.amap.api.services.weather.WeatherSearchQuery
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.ext.initClose
import com.gexiaobao.pigeon.app.ext.showMessage
import com.gexiaobao.pigeon.app.model.bean.RaceDetailInfoResponse
import com.gexiaobao.pigeon.app.util.CycleSender
import com.gexiaobao.pigeon.app.util.DatetimeUtil
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.SettingUtil
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.databinding.FragmentRaceInfoBinding
import com.gexiaobao.pigeon.ui.activity.ActivityGameResult
import com.gexiaobao.pigeon.ui.race.RaceViewModel
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.LogUtils
import me.hgj.jetpackmvvm.util.startActivity
import java.text.DecimalFormat
import java.util.Date

/**
 * @Author      : hxw
 * @Date        : 2023/6/1 10:36
 * @Describe    : 比赛详情信息
 */
class FragmentRaceInfo : BaseFragment<RaceViewModel, FragmentRaceInfoBinding>(), WeatherSearch.OnWeatherSearchListener {

    private var mId = 0
    private var mMapId = 0
    private var memberCode = ""//获取棚号
    private var title = "这是比赛名称"
    private var passStatus: String = ""
    private lateinit var mResultData: RaceDetailInfoResponse
    private var sunTimeList: ArrayList<String> = arrayListOf()

    //查询实时天气相关
    private var weatherlive: LocalWeatherLive? = null
    private lateinit var mQuery: WeatherSearchQuery
    private lateinit var mWeatherSearch: WeatherSearch

    private var flyDistance: Double = 0.0
    private var flyTime = ""

    //获取当前时间String
    private var currentStr = ""

    //获取当前时间date
    private lateinit var curDate: Date
    private var mFlyingState = 0

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.viewmodel = mViewModel
        mId = requireArguments().getInt("id")
        title = arguments?.getString("title").toString()
        passStatus = arguments?.getString("passStatus").toString()
        mViewModel.flyingState.set(passStatus == "6")
        mDatabind.includeBar.toolbar.initClose(title) {
            nav().navigateUp()
        }

        mDatabind.swipeRefreshView.init {
            showLoading(getString(R.string.loading))
            mViewModel.getPassDetailApp(mId.toString())
        }

    }

    override fun initData() {
        super.initData()
        mResultData = RaceDetailInfoResponse()
        searchLiveWeather()
    }

    private fun searchLiveWeather() {
        mQuery = WeatherSearchQuery("青岛市", WeatherSearchQuery.WEATHER_TYPE_LIVE) //检索参数为城市和天气类型，实时天气为1、天气预报为2
        try {
            mWeatherSearch = WeatherSearch(context)
            mWeatherSearch.setOnWeatherSearchListener(this)
            mWeatherSearch.query = mQuery
            mWeatherSearch.searchWeatherAsyn() //异步搜索
        } catch (e: AMapException) {
            e.printStackTrace()
        }
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(
            mDatabind.raceDetailGeneralFlyedMap,
            mDatabind.raceDetailGeneralCarMap,
            mDatabind.raceDetailGeneralRaceResult,
            mDatabind.raceDetailGeneralCollectionPigDetail
        ) {
            when (it) {
                mDatabind.raceDetailGeneralFlyedMap -> {
                    if (passStatus.toInt() < 6) {
                        showMessage("关卡未放飞，稍后查看")
                        return@setOnclickNoRepeat
                    }
                    nav().navigateAction(R.id.action_to_race_training_map, Bundle().apply {
                        putInt("mId", mId)
                        putString("title", title)
                    })
                }

                mDatabind.raceDetailGeneralCarMap -> {
                    nav().navigateAction(R.id.action_to_car_vehicle_route, Bundle().apply {
                        putString("title", title)
                        putInt("id", mMapId)
                    })
                }

                mDatabind.raceDetailGeneralRaceResult -> {
                    startActivity<ActivityGameResult>("title" to title, "passId" to mMapId, "type" to "race")
                    activity?.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out)
                }

                mDatabind.raceDetailGeneralCollectionPigDetail -> {
                    nav().navigateAction(R.id.action_to_sign_up_detail, Bundle().apply {
                        putString("title", title)
                        putString("memberCode", memberCode)
                        putInt("id", mMapId)
                    })
                }
            }
        }
    }

    override fun lazyLoadData() {
        super.lazyLoadData()
        showLoading(getString(R.string.loading))
        mViewModel.getMemberNum(mId.toString())
        mViewModel.getPassDetailApp(mId.toString())
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.detailInfoResult.observe(viewLifecycleOwner) {
            dismissLoading()
            if (mDatabind.swipeRefreshView.isRefreshing) {
                mDatabind.swipeRefreshView.isRefreshing = false
            }
            if (it != null) {
                flyTime = it.flyTime
                flyDistance = it.flyDis.toDouble()
                mResultData = it
                mMapId = it.id
                mViewModel.gatherPigeonsTime.set(it.loadTime)
                mViewModel.gatherPigeonsAddress.set(it.loadPlace)
                mViewModel.gatherPigeonsMobile.set(it.loadPhone)
                mViewModel.trainingPigeonsTime.set(flyTime)
                mViewModel.trainingPigeonsAddress.set(it.flyPlace)
                mViewModel.signUpFeatherNum.set(it.signNum)
                mViewModel.intoCageFeatherNum.set(it.loadedNum)
                mViewModel.homingNum.set(it.backNum)
                mViewModel.trainingWeather.set(it.weather)
                mViewModel.airTemperature.set(it.temperature)
                mViewModel.windPower.set(it.wind.trim())
                mViewModel.gap.set(it.flyDis)
                mViewModel.longitude.set(it.flyLonShow)
                mViewModel.latitude.set(it.flyLatShow)
                mViewModel.refereeZ.set(it.headReferee)
                mViewModel.refereeY.set(it.referee)
                mViewModel.pilot.set(it.flyMan)
                mViewModel.validPigeonsSpeed.set(it.effSpeed.toString() + "米/分")
                mFlyingState = it.passStatus
                mViewModel.flyingState.set(mFlyingState == 6)
                if (mFlyingState == 6) {
                    getCalculateSpeed(it)
                }
            } else {
                RxToast.showToast("未获取到信息")
            }
        }

        mViewModel.memberNumResult.observe(viewLifecycleOwner) {
            if (it != null) {
                memberCode = it.memberNum
            }
        }
    }

    private fun getCalculateSpeed(it: RaceDetailInfoResponse) {
        currentStr = DatetimeUtil.getTimeString()
        curDate = DatetimeUtil.getCustomTime(currentStr)
        sunTimeList.clear()
        //循环读取日出日落时间并进行处理 +-30分钟
        it.sun.forEachIndexed { index, s ->
            if (index % 2 == 0) {//偶数
                DatetimeUtil.getOldAndNewTime(DatetimeUtil.getCustomTime(s), 30)?.let { it1 -> sunTimeList.add(it1) }
            } else {
                DatetimeUtil.getOldAndNewTime(DatetimeUtil.getCustomTime(s), -30)?.let { it1 -> sunTimeList.add(it1) }
            }
        }
        //新list中的0位置添加一条数据（司放时间）
        sunTimeList.add(0, it.flyTime)
        if (sunTimeList.isNotEmpty() && sunTimeList.size >= 2) {
            //判断当前是否在有效时间段内，若不在直接return
            if (curDate.before(DatetimeUtil.getCustomTime(sunTimeList[0])) || curDate.after(
                    DatetimeUtil.getCustomTime(sunTimeList[sunTimeList.size - 1])
                )
            ) {
                mViewModel.gatherPigeonsSpeed.set("暂停计时")
                return
            }
        }
        getTimeCost()
//        val cTime = DatetimeUtil.getTimeString()
//        val second = DatetimeUtil.getTimeDifferenceSecond(cTime, flyTime)
//        val flyTotalTime = second - nightHoursCount
//        val result = DatetimeUtil.getCurrentTimeStamp(flyTotalTime.toInt())
//        LogUtils.debugInfo("jjjjjjjjj--->>$result")
    }

    private var nightHoursCount: Long = 0
    private var nightTimeCount = 0
    private fun getTimeCost() {
        nightHoursCount = 0
        //循环新list
        for (j in 0 until sunTimeList.size) {
            if (j == sunTimeList.size - 1) {//循环到列表的最后一条不再循环直接跳出
                mViewModel.gatherPigeonsSpeed.set("暂停计时")
                return
            }
            if (j % 2 != 0) {//判断下标为偶数或者基数，偶数代表白天  基数代表晚上
                nightTimeCount = DatetimeUtil.getTimeDifferenceSecond(sunTimeList[j + 1], sunTimeList[j]).toInt()
                nightHoursCount += nightTimeCount
                mViewModel.gatherPigeonsSpeed.set("暂停计时")
                continue
            } else {
                if (curDate.after(DatetimeUtil.getCustomTime(sunTimeList[j])) && curDate.before(
                        DatetimeUtil.getCustomTime(sunTimeList[j + 1])
                    )
                ) {
                    //循环执行代码块
                    CycleSender.INSTANCE.start({ _, _ ->
                        /**
                         * 1、执行周期循环的任务
                         * 2、循环获取最新的当前时间
                         * 3、计算分速
                         * 4、显示UI
                         * */
                        currentStr = DatetimeUtil.getTimeString()
                        //获取时间差总秒数
                        val second = DatetimeUtil.getTimeDifferenceSecond(currentStr, sunTimeList[0])
                        val countTime = (second - nightHoursCount).toDouble()//减去夜晚的时间
                        //如果当前时间在第一组日出日落时间范围内，当前时间-日出时间=飞行时间，参考空距/飞行时间 = 分速
                        val resultSpeed = SettingUtil.div(flyDistance * 1000, countTime, 5)
                        //当前时间-放飞时间-日落时间 = 飞行时间
                        val diffTime = DatetimeUtil.getTimeDifferenceMinute(currentStr, flyTime).toInt() //- nightTimeCount
                        val tString = Util.sub((diffTime * 60).toString(), nightTimeCount.toString())
//                        val flyTimeResult = DatetimeUtil.getCurrentTimeStamp(tString.toInt())
                        val flyTimeResult = DatetimeUtil.convertMillisToHoursAndMinutes(tString.toLong() * 1000)
                        LogUtils.debugInfo("jjj<->$diffTime<->$tString<->$flyTimeResult")
                        val result = DecimalFormat("#.00000")
                        MainScope().launch {
                            mViewModel.gatherPigeonsSpeed.set(result.format(resultSpeed * 60) + "米/分")
                            mViewModel.gatherPigeonsFLyTime.set(flyTimeResult)
                        }
                        LogUtils.debugInfo(resultSpeed.toString() + "米/分" + "<<----->>" + flyTimeResult)
                        //循环获取当前日期 转换为date类型  循环比较与list中的时间段，若超出当前范围则重新开始循环
                        if (DatetimeUtil.getCustomTime(currentStr).after(DatetimeUtil.getCustomTime(sunTimeList[sunTimeList.size - 1]))) {
                            CycleSender.INSTANCE.stop()
                            getTimeCost()
                        }
                    }, 2)//间隔2秒循环一次
                    return
                } else {
                    CycleSender.INSTANCE.stop()
                }
            }
        }
    }

    /**
     * 实时天气查询回调
     */
    override fun onWeatherLiveSearched(weatherLiveResult: LocalWeatherLiveResult?, rCode: Int) {
        if (rCode == AMapException.CODE_AMAP_SUCCESS) {
            if (weatherLiveResult?.liveResult != null) {
                weatherlive = weatherLiveResult.liveResult
            } else {
                RxToast.showToast("对不起，没有搜索到相关数据")
            }
        } else {
            RxToast.showToast(rCode.toString())
        }
    }

    override fun onWeatherForecastSearched(p0: LocalWeatherForecastResult?, p1: Int) {

    }

    override fun onDestroyView() {
        super.onDestroyView()
        CycleSender.INSTANCE.stop()
    }
}